package com.magist.manage.copyrights.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.magist.core.controller.BaseController;
import com.magist.core.entity.CxtHolder;
import com.magist.core.entity.ResultMessage;
import com.magist.core.exception.BusinessException;
import com.magist.core.util.BeanCopyUtil;
import com.magist.core.util.DateUtil;
import com.magist.core.util.ExcelUtil;
import com.magist.manage.copyrights.dto.AppendixProjectDto;
import com.magist.manage.copyrights.dto.SupplyContractDto;
import com.magist.manage.copyrights.entity.AppendixProject;
import com.magist.manage.copyrights.entity.ContractBalance;
import com.magist.manage.copyrights.entity.ContractRights;
import com.magist.manage.copyrights.entity.Copyrights;
import com.magist.manage.copyrights.entity.SupplyContract;
import com.magist.manage.copyrights.entity.SupplyInfo;
import com.magist.manage.copyrights.export.SupplyContractExportDto;
import com.magist.manage.copyrights.importExcel.SupplyContractImportDto;
import com.magist.manage.copyrights.service.AppendixProjectService;
import com.magist.manage.copyrights.service.ContractBalanceService;
import com.magist.manage.copyrights.service.ContractRightsService;
import com.magist.manage.copyrights.service.CopyrightsService;
import com.magist.manage.copyrights.service.SupplyContractService;
import com.magist.manage.copyrights.service.SupplyInfoService;
import com.magist.manage.enums.ContractTypeEnum;
import com.magist.manage.enums.ValidStatusEnum;
import com.magist.manage.util.AuthFilterUtil;
import com.magist.manage.web.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(value="供应商合同接口",tags={"供应商合同接口"})
@RestController
@RequestMapping("/rest/supplyContract")
public class RestSupplyContractController extends BaseController {

    @Autowired
    private SupplyContractService supplyContractService;
    @Autowired
    private ContractBalanceService contractBalanceService;
    @Autowired
    private AppendixProjectService appendixProjectService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private CopyrightsService copyrightsService;
    @Autowired
    private ContractRightsService contractRightsService;
    @Autowired
    private SupplyInfoService supplyInfoService;

    @ApiOperation(value = "保存", notes = "保存接口")
    @RequestMapping(value = "save.do", method = RequestMethod.POST)
    public Object save(@RequestBody SupplyContractDto supplyContractDto) {
        supplyContractService.addContract(supplyContractDto);

        return ResultMessage.success();
    }


    @ApiOperation(value = "更新", notes = "更新接口")
    @RequestMapping(value = "update.do", method = RequestMethod.POST)
    public Object update(@RequestBody SupplyContractDto supplyContractDto) {
        SupplyContract oldSupplyContract = supplyContractService.getById(supplyContractDto.getId());
        if (oldSupplyContract == null)
            throw new BusinessException("无效的数据!");
        ResultMessage result = null;

        if (supplyContractService.updateSupplyContract(supplyContractDto) > 0)
            result = ResultMessage.success("操作成功");
        else
            result = ResultMessage.error("操作失败!");
        return result;
    }

    @ApiOperation(value = "列表", notes = "分页查询接口")
    @RequestMapping(value = "page.do", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "compoundSearch", value = "合同编号/合同名称/供应商简称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "合同编号/合同名称/供应商简称", required = false, dataType = "String"),
    })
    public Object page(@ModelAttribute("supplyContractDto") SupplyContractDto supplyContractDto) {
        ResultMessage result = ResultMessage.success();
        Example example = new Example(SupplyContract.class);
        example = packExample(example, supplyContractDto);
        AuthFilterUtil.doAddAuthCondition(example,userInfoService.getById(CxtHolder.getUser().getUserId()));
        PageInfo<SupplyContract> pageInfo = supplyContractService.page(example, getPageInfo());
        // 修改人&过期状态set
        List<SupplyContract> list = pageInfo.getList();
        PageInfo<SupplyContractDto> pageInfo2 = new PageInfo<SupplyContractDto>();
        BeanUtils.copyProperties(pageInfo, pageInfo2);
        if (!CollectionUtils.isEmpty(list)) {
            ArrayList<SupplyContractDto> supplyContractDtos = new ArrayList<>();
            for (SupplyContract supplyContract : list) {

                SupplyContractDto contractDto = BeanCopyUtil.copy(supplyContract, SupplyContractDto.class);
                String modifyById = supplyContract.getModifyById();

                Date now = new Date();
                Date endDate = supplyContract.getEndDate();
                String expireStatus = null;
                int monthDiff = DateUtil.getMonthDiff( endDate,now);
                if (monthDiff == 0) {
                    expireStatus = "1个月内到期";
                } else if (monthDiff > 0 && monthDiff < 3) {
                    expireStatus = "3个月内到期";
                } else if (monthDiff >= 3 && monthDiff < 6) {
                    expireStatus = "6个月内到期";
                } else if (monthDiff >= 6) {
                    expireStatus = "6个月以外到期";
                }
                if (now.after(endDate)) {
                    expireStatus = "已到期";
                }
                contractDto.setExpireStatus(expireStatus);
                supplyContractDtos.add(contractDto);
            }

            pageInfo2.setList(supplyContractDtos);
        }

        result.setContent(pageInfo2);
        return result;
    }

    @ApiOperation(value = "删除", notes = "删除接口")
    @RequestMapping(value = "del.do", method = RequestMethod.POST)
    public Object del(@ModelAttribute("id") String id) {
        SupplyContract supplyContract = supplyContractService.getById(id);
        if (supplyContract == null)
            throw new BusinessException("无效的数据!");
        ResultMessage result = null;
        if (supplyContractService.delete(supplyContract) > 0)
            result = ResultMessage.success("操作成功");
        else
            result = ResultMessage.error("操作失败!");
        return result;
    }

    @ApiOperation(value = "失效合同", notes = "失效合同")
    @RequestMapping(value = "invalidContract.do", method = RequestMethod.POST)
    public Object invalidContract(@ModelAttribute("id") String id) {
        SupplyContract supplyContract = supplyContractService.getById(id);
        if (supplyContract == null)
            throw new BusinessException("无效的数据!");
        ResultMessage result = null;
        if (supplyContractService.doInvalidContract(id) > 0)
            result = ResultMessage.success("操作成功");
        else
            result = ResultMessage.error("操作失败!");
        return result;
    }

    @ApiOperation(value = "详情", notes = "详情接口")
    @RequestMapping(value = "info.do", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "合同id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "opt", value = "操作类型(info:查看详情)", required = false, dataType = "String"),
    })
    public Object info(@ModelAttribute("id") String id,String contractNo, String opt) {
        SupplyContract supplyContract = null;
        if(!StringUtils.isEmpty(id))
            supplyContract = supplyContractService.getById(id);
        if(!StringUtils.isEmpty(contractNo))
        supplyContract = supplyContractService.findByContractNo(contractNo);
        if (supplyContract == null)
            throw new BusinessException("无效的数据!");
        id = supplyContract.getId();
        SupplyContractDto supplyContractDto = new SupplyContractDto();
        BeanUtils.copyProperties(supplyContract, supplyContractDto);
        // 三方信息
        ContractBalance contractBalance = contractBalanceService.getByContractId(id);
        if (!ObjectUtils.isEmpty(contractBalance)) {
            supplyContractDto.setPartyOne(contractBalance.getPartyOne());
            supplyContractDto.setPartyTwo(contractBalance.getPartyTwo());
            supplyContractDto.setPartyThree(contractBalance.getPartyThree());
            supplyContractDto.setPartyOneNum(contractBalance.getPartyOneNum());
            supplyContractDto.setPartyTwoNum(contractBalance.getPartyTwoNum());
            supplyContractDto.setPartyThreeNum(contractBalance.getPartyThreeNum());

        }
        // 附件信息
        List<AppendixProject> appendixProjects = appendixProjectService.findByProjectId(id);
        List<AppendixProjectDto> appendixProjectDtos = BeanCopyUtil.copy(appendixProjects, AppendixProjectDto.class);
        BeanUtils.copyProperties(appendixProjects, appendixProjectDtos);
        supplyContractDto.setAppendixProjects(appendixProjectDtos);
        // 若是详情,拉取版权&授权信息
        if ("info".equals(opt)) {
            List<Copyrights> copyrights = copyrightsService.findByContractNo(supplyContract.getContractNo());
            List<ContractRights> contractRights = contractRightsService.findByContractNo(supplyContract.getContractNo());
            supplyContractDto.setCopyrights(copyrights);
            supplyContractDto.setContractRights(contractRights);
        }
        ResultMessage result = ResultMessage.success();
        result.setContent(supplyContractDto);
        return result;
    }

    @ApiOperation(value = "判断合同时间", notes = "判断合同时间(剩余有效期是否大于6个月)")
    @PostMapping(value = "checkContractDate.do")
    public Object checkContractDate(@ModelAttribute("contractNo") String contractNo) {
        ResultMessage result = supplyContractService.checkContractDate(contractNo);

        return result;
    }

    private Example packExample(Example example, SupplyContractDto supplyContractDto) {
        Date now = new Date();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deleted", "F");
        if (StringUtils.isNotEmpty(supplyContractDto.getId()))
            criteria.andEqualTo("id", supplyContractDto.getId());
        // 到期状态
        String expireStatus = supplyContractDto.getExpireStatus();
        if (StringUtils.isNotEmpty(expireStatus)) {
            if (expireStatus.equals("0")) {
                criteria.andLessThanOrEqualTo("endDate", now);
            } else if (Integer.valueOf(expireStatus) > 6) {
                criteria.andGreaterThanOrEqualTo("endDate", DateUtil.addMonths(now, 6));
            } else {
                criteria.andBetween("endDate", now, DateUtil.addMonths(now, Integer.valueOf(supplyContractDto.getExpireStatus())));
            }
        }
        // 结算形式
        if (StringUtils.isNotEmpty(supplyContractDto.getBalanceType()))
            criteria.andEqualTo("balanceType", supplyContractDto.getBalanceType());
        // 合同状态
        if (StringUtils.isNotEmpty(supplyContractDto.getContractStatus()))
            criteria.andEqualTo("contractStatus", supplyContractDto.getContractStatus());
        // 合同类型
        if (StringUtils.isNotEmpty(supplyContractDto.getContractType()))
            criteria.andEqualTo("contractType", supplyContractDto.getContractType());
        // 合同编号/合同名称/供应商简称赋值
        String compoundSearch = supplyContractDto.getCompoundSearch();
        if(!StringUtils.isEmpty(compoundSearch)) {
            Example.Criteria criteria2 = example.createCriteria();
            criteria2.orLike("contractNo", "%" +compoundSearch+"%");
            criteria2.orLike("contractName", "%" +compoundSearch+"%");
            criteria2.orLike("supplyName", "%" +compoundSearch+"%");
            example.and(criteria2);
        }

        return example;
    }


    /**
     * 合同列表,通过合同编号模糊查询
     * @param contractNo
     * @return
     */
    @ApiOperation(value="合同列表", notes="合同列表,通过合同编号模糊查询")
    @PostMapping(value = "fetchContractList.do")
    public Object fetchContractList(@ModelAttribute("contractNo") String contractNo,String copyrightsId,String supplyId) {
        ResultMessage result = ResultMessage.success();
        Example example = new Example(SupplyContract.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deleted", "F");
        criteria.andEqualTo("contractStatus", ValidStatusEnum.VALID.getCode());
        if(!StringUtils.isEmpty(contractNo))
            criteria.andLike("contractNo", "%" + contractNo + "%");
        if(!StringUtils.isEmpty(copyrightsId)) {
            Copyrights copyrights = copyrightsService.getById(copyrightsId);
            if(ObjectUtils.isEmpty(copyrights)) {
                return result;
            }
            String contractNo1 = copyrights.getContractNo();
            criteria.andEqualTo("contractNo", contractNo1);
        }
        if(!StringUtils.isEmpty(supplyId)) {
            SupplyInfo supplyInfo = supplyInfoService.getById(supplyId);
            if(ObjectUtils.isEmpty(supplyInfo)) {
                return result;
            }
            criteria.andEqualTo("supplyId", supplyId);
        }
        List<SupplyContract> supplyContracts = supplyContractService.find(example);
        // 合同结算信息
        List<SupplyContractDto> supplyContractDtos = new ArrayList<>();
        for (SupplyContract supplyContract : supplyContracts) {
            SupplyContractDto supplyContractDto = BeanCopyUtil.copy(supplyContract, SupplyContractDto.class);
            ContractBalance contractBalance = contractBalanceService.getByContractId(supplyContract.getId());
            supplyContractDto.setPartyOne(contractBalance.getPartyOne());
            supplyContractDto.setPartyTwo(contractBalance.getPartyTwo());
            supplyContractDto.setPartyThree(contractBalance.getPartyThree());
            supplyContractDto.setPartyOneNum(contractBalance.getPartyOneNum());
            supplyContractDto.setPartyTwoNum(contractBalance.getPartyTwoNum());
            supplyContractDto.setPartyThreeNum(contractBalance.getPartyThreeNum());

            Date now = new Date();
            Date endDate = supplyContract.getEndDate();
            String expireStatus = supplyContractDto.getExpireStatus();
            int monthDiff = DateUtil.getMonthDiff( endDate,now);
            if (monthDiff == 0) {
                expireStatus = "1个月内到期";
            } else if (monthDiff > 0 && monthDiff < 3) {
                expireStatus = "3个月内到期";
            } else if (monthDiff >= 3 && monthDiff < 6) {
                expireStatus = "6个月内到期";
            } else if (monthDiff >= 6) {
                expireStatus = "6个月以外到期";
            }
            if (now.after(endDate)) {
                expireStatus = "已到期";
            }
            supplyContractDto.setExpireStatus(expireStatus);
            supplyContractDtos.add(supplyContractDto);
        }
        result.setContent(supplyContractDtos);
        return result;
    }

    @ApiOperation(value = "批量失效合同", notes = "批量失效合同")
    @RequestMapping(value = "batchInvalid.do", method = RequestMethod.POST)
    public Object batchInvalid(@ModelAttribute("invalidIds") String invalidIds) {
        if(StringUtils.isEmpty(invalidIds)) {
            throw new BusinessException("未选择失效数据");
        }
        String[] invalids = invalidIds.split(",");
        ResultMessage result = null;
        for (String id : invalids) {
            SupplyContract supplyContract = supplyContractService.getById(id);
            if (supplyContract == null)
                throw new BusinessException("无效的数据!");

            if (supplyContractService.doInvalidContract(id) > 0)
                result = ResultMessage.success("操作成功");
            else {
                result = ResultMessage.error("操作失败!");
                return result;
            }
        }
        return result;
    }


    @ApiOperation(value="excel导出", notes="excel导出")
    @RequestMapping(value = "exportExcel.do", method = RequestMethod.GET)
    public void exportExcel(@ModelAttribute("supplyContractDto") SupplyContractDto supplyContractDto, HttpServletResponse response) {
        Example example = new Example(SupplyContract.class);
        example = packExample(example, supplyContractDto);
        AuthFilterUtil.doAddAuthCondition(example,userInfoService.getById(CxtHolder.getUser().getUserId()));
        PageHelper.startPage(1, Integer.MAX_VALUE-1,"SHOW_ID DESC");
        List<SupplyContract> list = supplyContractService.find(example);
        List<SupplyContractExportDto> supplyContractDtos = new ArrayList<SupplyContractExportDto>();
        if (!CollectionUtils.isEmpty(list)) {
            for (SupplyContract supplyContract : list) {

                SupplyContractExportDto contractDto = BeanCopyUtil.copy(supplyContract, SupplyContractExportDto.class);

                Date now = new Date();
                Date endDate = supplyContract.getEndDate();
                String expireStatus = null;
                int monthDiff = DateUtil.getMonthDiff( endDate,now);
                if (monthDiff == 0) {
                    expireStatus = "1个月内到期";
                } else if (monthDiff > 0 && monthDiff < 3) {
                    expireStatus = "3个月内到期";
                } else if (monthDiff >= 3 && monthDiff < 6) {
                    expireStatus = "6个月内到期";
                } else if (monthDiff >= 6) {
                    expireStatus = "6个月以外到期";
                }
                if (now.after(endDate)) {
                    expireStatus = "已到期";
                }
                contractDto.setExpireStatus(expireStatus);
                supplyContractDtos.add(contractDto);
            }
        }

        //导出操作
        String contractType = supplyContractDto.getContractType();
        String pre = "";
        if (ContractTypeEnum.IN.getCode().equals(contractType)) {
            pre = "版权引入";
        } else if (ContractTypeEnum.OUT.getCode().equals(contractType)) {
            pre = "版权输出";
        }
        ExcelUtil.exportExcel(supplyContractDtos,pre +"合同列表",pre +"合同列表",SupplyContractExportDto.class,DateUtil.toString(new Date(),DateUtil.yyyy_MM_dd)+ pre +"合同列表.xls",response);
    }


    @ApiOperation(value="excel导入", notes="excel导入,模板下载路径(47.96.144.33:8080/合同导入模板.xlsx)")
    @PostMapping("importExcel.do")
    public Object importExcel(@RequestParam(value="file") MultipartFile file){
        List<SupplyContractImportDto> supplyContractImportDto = ExcelUtil.importExcel(file, 6, 1, SupplyContractImportDto.class);
        List<SupplyContractDto> supplyContractDtos = BeanCopyUtil.copy(supplyContractImportDto, SupplyContractDto.class);
        supplyContractService.doBatchAdd(supplyContractDtos);
        return ResultMessage.success();
    }
}
